(function($) {
    // 表单验证
    $.validator.setDefaults();
    var u = Util.AjaxRUrl + 'uploadFile';
    if (epointuser.type == "个人注册"||epointuser.type == "人才注册") {
        $(".rpinfo").show();
        //console.log(epointuser.type);
        $("#form").validate({
            rules: {
                userxm: "required",
                usersfz: "required"
            },
            messages: {
                userxm: "",
                usersfz: ""
            }
        });
		$("#birthday").datetimepicker({
                minView: 'month',
                format: "yyyy-mm-dd",
                language: "zh-CN",
                autoclose: true,
                // startDate: new Date(),
                escape: false
        });
		$("#graduationtime").datetimepicker({
                minView: 'month',
                format: "yyyy-mm-dd",
                language: "zh-CN",
                autoclose: true,
                // startDate: new Date(),
                escape: false
        });
		$("#hiredate").datetimepicker({
                minView: 'month',
                format: "yyyy-mm-dd",
                language: "zh-CN",
                autoclose: true,
                // startDate: new Date(),
                escape: false
        });
        uploadInit("pfilePicker1", "pfilebox1", "sfzzm", u);
        uploadInit("pfilePicker2", "pfilebox2", "sfzfm", u);
    } else if (epointuser.type == "企业注册") {
        $(".reinfo").show();
        //企业类型：默认显示工业类型
        $(".selectb select").change(function(event) {
            var v = $(this).val();
            switch (v) {
                case "1":
                    $(".selectb").parent().siblings('.tabrdo').hide();
                    $(".selectb").parent().siblings('.gy').show();
                    break;
                case "2":
                    $(".selectb").parent().siblings('.tabrdo').hide();
                    $(".selectb").parent().siblings('.fwy').hide();
					$("#fwyScale").parent().show();
                    break;
                default:
                    $(".selectb").parent().siblings('.tabrdo').hide();
                    break;
            }
        });
		$("#rdogxy").click(function(){
			$("#gqzsno").parent().show();
			$("#fzdate").parent().show();
		});
		$("#rdogxn").click(function(){
			$("#gqzsno").parent().hide();
			$("#fzdate").parent().hide();
		});
        //加载规模数据：
        $.ajax({
            url: Util.AjaxRUrl + 'enterpriseScale',
            type: "post",
            dataType: "json",
            data: {
                param: '{}'
            },
            success: function(rdata) {
                if (rdata.enterpriseScale) {
                    var shtml = "";
                    var flag = true;
                    for (var i = 0; i < rdata.enterpriseScale.length; i++) {
                        if (epointuser.scale == rdata.enterpriseScale[i].scale) { //epointuser优先加载获取
                            flag = false;
                            shtml += '<input type="radio" name="scale" id="gm' + rdata.enterpriseScale[i].rowGuid + '" class="ewb-g-radio l" value="' + rdata.enterpriseScale[i].rowGuid + '" checked="true">' + '<label for="gm' + rdata.enterpriseScale[i].rowGuid + '" class="ewb-g-lab2 l">' + rdata.enterpriseScale[i].scale + '</label>';
                        } else {
                            shtml += '<input type="radio" name="scale" id="gm' + rdata.enterpriseScale[i].rowGuid + '" class="ewb-g-radio l" value="' + rdata.enterpriseScale[i].rowGuid + '">' + '<label for="gm' + rdata.enterpriseScale[i].rowGuid + '" class="ewb-g-lab2 l">' + rdata.enterpriseScale[i].scale + '</label>';
                        }

                    }
                    $("#scaresection").html(shtml);
                    if (flag) {
                        $("#scaresection input").first().prop("checked", true);
                    }
                } else {
                    $(".ewb-confirm").hide(); //屏蔽提交按钮
                }
            },
            error: function(XMLHttpRequest, txtStatus, errorThrown) {
                $(".ewb-confirm").hide();
                //console.log(XMLHttpRequest);
            }
        });
        //console.log(epointuser.type);
        $("#form").validate({
            rules: {
				tyshxyCode:{
					required: true,
					isshxym: true
				},
                unitName: "required",
                fddbrName: "required",
                registAddress: "required",
                registCapital: {
                    required: true,
                    isFloat: true
                },
                fddbrID: "required",
                gqzsno: {
                    isGQ: true
                },
                fzdate: {
                    isGQDate: true
                }
            },
            messages: {
				tyshxyCode:{
                    required:"",
                    isshxym:"*格式不正确"
                },
                unitName: "",
                fddbrName: "",
                registAddress: "",
                registCapital:{
                    required:"",
                    isFloat:"*数字"
                },
                fddbrID: "",
                gqzsno: "",
                fzdate: {
                    isGQDate: "非有效发证日期"
                }
            }
        });
        $.validator.addMethod('isFloat', function(value, element) {
            var reg = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/;
            if (value == "") {
                return this.optional(element);
            } else {
                var f=reg.test(value);
                return this.optional(element) || reg.test(value);
            }
        }, '*数字');
        //高企发证日期验证
        $.validator.addMethod('isGQDate', function(value, element) {
            var gq = $("#rdogxy").is(":checked");
            if (gq) {
                var ept = false;
                if ($.trim(value) != "") {
                    var iptdate = Util.stringToDate(value);
                    var tnow = new Date();
                    tnow.setYear(tnow.getFullYear() - 3);
                    if (iptdate >= tnow) { //3 year valid
                        ept = true;
                    } else {
                        this.optional(element);
                    }
                }
                return ept;
            } else {
                return true;
            }
        }, "非有效发证日期");
        //高企非空验证
        $.validator.addMethod('isGQ', function(value, element) {
            var gq = $("#rdogxy").is(":checked");
            if (gq) {
                var ept = false;
                if ($.trim(value) != "") {
                    ept = true
                }
                return ept;
            } else {
                return true;
            }
        }, "");
        $("#fzdate").datetimepicker({
                minView: 'month',
                format: "yyyy-mm-dd",
                language: "zh-CN",
                autoclose: true,
                // startDate: new Date(),
                escape: false
            })
            //test:
            // var u = '/apis/hfesewb/rest/hfService/userInfo';
            // var ul1= uploadInit("filePicker1", "filebox1", '{userGuid:"'+$.cookie("the_userid")+'"}',u, true);
        uploadInit("filePicker1", "filebox1", "eyyzz", u);
        //var guid= WebUploader.Base.guid();
        uploadInit("filePicker2", "filebox2", "eswdj", u);
        uploadInit("filePicker3", "filebox3", "ezzjg", u);
    }else{
		$(".zjinfo").show();
		$("#form").validate({
			rules: {
				zjuserxm: "required",
				zjusersfz:{
					required: true,
					iscardid: true
				}
			},
			messages: {
				zjuserxm: "",
				zjusersfz: ""
			}
		});
		$("#zjbirthday").datetimepicker({
				minView: 'month',
				format: "yyyy-mm-dd",
				language: "zh-CN",
				autoclose: true,
				// startDate: new Date(),
				escape: false
		});
		 uploadInit("zjfilePicker1", "zjfilebox1", "EXPERT_PIC", u);
		 uploadInit("zjfilePicker2", "zjfilebox2", "EXPERT_PIC", u);
		 uploadInit("zjfilePicker3", "zjfilebox3", "EXPERT_PIC", u);
	}
	
	$.validator.addMethod('isshxym', function(value, element) {  
		var valided = false;
		valided = checkSXCode(value);
		
        return this.optional(element) || valided;
    }, '格式不正确'); //需字母开头,数字和下划线
	
	$.validator.addMethod('iscardid', function(value, element) {
        var valided = false;
        valided = identityCodeValid(value.toUpperCase());
        return this.optional(element) || valided;
    }, '格式不正确');
	
	function checkSXCode(SXCode) {
        var CODE1 = SXCode;
        var CODE = CODE1.substring(8, 17);
        var patrn1 = /^[0-9A-Z]+$/; //大小写
        if ((CODE1.length != 18) || (patrn1.test(CODE1) == false)) {
            //alert("统一社会信用代码不能输入小写");
            return false;
        } else {
            var patrn = /^[0-9A-Z]+$/;
            if (patrn.test(CODE) == false) {
                //alert("统一社会信用代码不正确");
                return false;
            } else {
                var lastpatrn = /^[0-9X]+$/;
                var checkcode = CODE.substring(8, 9);
                if (lastpatrn.test(checkcode) == false) {
                    //alert("统一社会信用代码不正确");
                    return false;
                } else {
                    var ancode;
                    var ancodevalue;
                    var total = 0;
                    var weightedfactors = [3, 7, 9, 10, 5, 8, 4, 2]; //加权因子
                    var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                    for (var i = 0; i < CODE.length - 1; i++) {
                        ancode = CODE.substring(i, i + 1);
                        ancodevalue = str.indexOf(ancode);
                        total = total + ancodevalue * weightedfactors[i];
                    }
                    var ucheckcode = 11 - total % 11;
                    if (ucheckcode == 10)
                        ucheckcode = 'X';
                    if (ucheckcode == 11)
                        ucheckcode = '0';
                    if (checkcode != ucheckcode) {
                        //alert("统一社会信用代码不正确");
                        return false;
                    }
                }
                return true;
            }
        }
    }
	
	function identityCodeValid(code) {
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" };
        var pass = true;
        if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
            pass = false;
        } else if (!city[code.substr(0, 2)]) {
            pass = false;
        } else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    pass = false;
                }
            }
        }
        return pass;
    }
	
	$("#personinfoedit").click(function(){
		layer.confirm('是否确认修改信息？', {
			//skin: 'layer-ext-moon', //加上边框
           // area: ['420px', '240px'], //宽高
			btn: ['确定','取消'] //按钮
				,icon: 6  // icon
				,yes:function(){
				//$('.ewb-confirm').click();
				layer.closeAll();
				$('.ewb-confirm').show();
			}
			,btn2:function(){
				layer.closeAll();
			}
		});
	});
    // 提交表单数据
    $('.ewb-confirm').on('click', function() {
        var formvalid = $("#form").valid();
        if (formvalid) {
            var the_userid = $.cookie('the_userid');
            var pms = $('#form').serializeObject();
            //个人认证
            if (epointuser.type == "个人注册"||epointuser.type=="人才注册") {
                //个人认证
                var fzm = $("#pfilebox1 .filedelete").length > 0 & ($("#pfilebox1 .filedelete").data("role") != "");
                var ffm = $("#pfilebox2 .filedelete").length > 0 & ($("#pfilebox2 .filedelete").data("role") != "");
                if (fzm == undefined) fzm = false;
                if (ffm == undefined) ffm = false;
                if (fzm && ffm) //附件验证
                {
                    $(".ewb-confirm").hide(); // forbinden more click
                    $.ajax({
                        url: Util.AjaxRUrl + 'personalCertification',
                        type: "post",
                        dataType: "json",
                        data: {
                            param: '{userGuid:"' + the_userid +
                                '",registContacts:"' + pms.registContacts +
                                '",mobile:"' + pms.mobile +
                                '",phone:"' + pms.phone +
                                '",QQ:"' + pms.QQ +
                                '",contactsAddress:"' + pms.contactsAddress +
                                '",name:"' + pms.userxm +
                                '",sex:"' + pms.rdosex +
                                '",personalID:"' + pms.usersfz +
                                '",birthday:"' + pms.birthday +
                                '",nativeplace:"' + pms.nativeplace +
                                '",address:"' + pms.address +
                                '",school:"' + pms.school +
                                '",major:"' + pms.major +
                                '",education:"' + pms.education +
                                '",degree:"' + pms.degree +
                                '",graduationtime:"' + pms.graduationtime +
                                '",hiredate:"' + pms.hiredate +
                                '",learnexperience:"' + pms.learnexperience +
                                '",workexperience:"' + pms.workexperience +
                                '"}'
                        },
                        success: function(data) {
                            if (data.returnInfo.isok == 1) {
                                alert("认证提交成功");
                                window.location = window.location;
                            } else {
                                alert("认证提交失败");
                                $(".ewb-confirm").show();
                            }
                        },
                        error: function(XMLHttpRequest, txtStatus, errorThrown) {
                            //console.log(XMLHttpRequest);
                        }
                    });
                } else {
                    alert("请上传身份证正反面图片");
                }

            } else if (epointuser.type == "企业注册") {
                if (pms.qyType != "1") {
                    pms.scale = "";
                }
                if (pms.qyType != "3") {
                    pms.fwyScare = "";
                }
                if(pms.zbdw==undefined||pms.zbdw==""){
                    pms.zbdw="元";
                }
                pms.registCapital=pms.registCapital+'万'+pms.zbdw;
                //企业认证
                $("#fzdate").focusout();
                if ($("#fzdate").hasClass("error")) { //处理readonly提交验证失效问题
                    return;
                }
                var yfv = $("#filebox1 .filedelete").length > 0 & ($("#filebox1 .filedelete").data("role") != "");
                var zfv = ($("#filebox2 .filedelete").length > 0 & ($("#filebox2 .filedelete").data("role") != "")) & ($("#filebox3 .filedelete").length > 0 & ($("#filebox3 .filedelete").data("role") != ""));
                if (yfv == undefined) yfv = false;
                if (zfv == undefined) zfv = false;
                if (yfv || zfv) //附件验证
                {
                    $(".ewb-confirm").hide(); // forbinden more click
                    $.ajax({
                        url: Util.AjaxRUrl + 'certification',
                        type: "post",
                        dataType: "json",
                        data: {
                            param: '{userGuid:"' + the_userid +
                                '",registContacts:"' + pms.registContacts +
                                '",mobile:"' + pms.mobile +
                                '",phone:"' + pms.phone +
                                '",QQ:"' + pms.QQ +
                                '",contactsAddress:"' + pms.contactsAddress +
                                '",tyshxyCode:"' + pms.tyshxyCode +
                                '",zzjgCode:"' + pms.zzjgCode +
                                '",gszcCode:"' + pms.gszcCode +
                                '",swdjCode:"' + pms.swdjCode +
                                '",unitName:"' + pms.unitName +
                                '",fddbrName:"' + pms.fddbrName +
                                '",fddbrID:"' + pms.fddbrID +
                                '",registAddress:"' + pms.registAddress +
                                '",registCapital:"' + pms.registCapital +
                                '",qyType:"' + pms.qyType +
                                '",scale:"' + pms.scale +
                                '",isyxqngjgxjsqy:"' + pms.isyxqngjgxjsqy +
                                '",gqzsno:"' + pms.gqzsno +
                                '",fzdate:"' + pms.fzdate +
								'",fwyScale:"' + pms.fwyscare3 +
                                '"}'
                        },
                        success: function(data) {
                            if (data.returnInfo) {
                                switch (data.returnInfo.isok) {
                                    case "1":
                                        alert("认证提交成功");
                                        window.location = window.location;
                                        break;
                                    case "2":
                                        alert("提交异常");
                                        break;
                                    case "3":
                                        alert("单位重复");
                                        $(".ewb-confirm").show();
                                        break;
                                    default:
                                        break;
                                }
                            } else {
                                alert("提交异常");
                            }
                        },
                        error: function(XMLHttpRequest, txtStatus, errorThrown) {
                            //console.log(XMLHttpRequest);
                        }
                    });
                } else {
                    alert("营业执照或（组织机构证和税务登记证）必传");
                }
            }else{
				$(".ewb-confirm").hide(); // forbinden more click
				$.ajax({
					url: Util.AjaxRUrl + 'expertCertification',
					type: "post",
					dataType: "json",
					data: {
						param: '{userGuid:"' + the_userid +
							'",registContacts:"' + pms.registContacts +
							'",mobile:"' + pms.mobile +
							'",phone:"' + pms.phone +
							'",QQ:"' + pms.QQ +
							'",contactsAddress:"' + pms.contactsAddress +
							'",name:"' + pms.zjuserxm +
							'",sex:"' + pms.zjrdosex +
							'",personalID:"' + pms.zjusersfz +
							'",email:"' + pms.zjemail +
							'",birthday:"' + pms.zjbirthday +
							'",age:"' + pms.zjage +
							'",school:"' + pms.zjschool +
							'",major:"' + pms.zjmajor +
							'",education:"' + pms.zjeducation +
							'",degree:"' + pms.zjdegree +
							'",techtitle:"' + pms.techtitle +
							'",techlevel:"' + pms.techlevel +
							'",workunit:"' + pms.workunit +
							'",resume:"' + pms.resume +
							'",yjcgryjl:"' + pms.yjcgryjl +
							'"}'
					},
					success: function(data) {
						if (data.returnInfo.isok == 1) {
							alert("认证提交成功");
							window.location = window.location;
						} else {
							alert("认证提交失败");
							$(".ewb-confirm").show();
						}
					},
					error: function(XMLHttpRequest, txtStatus, errorThrown) {
						//console.log(XMLHttpRequest);
					}
				});
			}


        }
    });

    //附件控件初始化
    function uploadInit(choseBtn, fileListCon, cTag, uploadUrl) {
        // 文件上传
        var $list = $("#" + fileListCon), // 文件容器
            $pickerBtn = $("#" + choseBtn), // 上传按钮
            limitSize = 5 * 1024 * 1024; // 单位B,大小？max 5M
        var allowType = ['gif', 'jpg', 'jpeg', 'bmp', 'png'];
        var uploader = WebUploader.create({
            // 自动上传。
            auto: true,
            // swf文件路径
            swf: '/js/lib/webuploader/Uploader.swf',
            // 文件接收服务端。
            server: uploadUrl,
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: {
                id: "#" + choseBtn,
                multiple: false
            },
            // 上传时携带的参数
            formData: {
                //param:params
            },
            accept: {
                title: 'Images',
                extensions: allowType.join(","),
                mimeTypes: 'image/*'
            },
            duplicate: true,
            fileNumLimit: 1, //+上传按钮控制次数
            fileSingleSizeLimit: limitSize
        });
        //console.log(uploader.options.formData);
        // 当文件被加入队列之前触发
        uploader.on('beforeFileQueued', function(file) {
            var ext = file.name.substr(file.name.lastIndexOf(".") + 1).toLowerCase();
            var size = file.size;
            // console.log(limitSize)
            uploader.options.formData.clengGuid = $.cookie("the_userid");
            uploader.options.formData.fileTag = cTag;
            if (size > limitSize) {
                alert("上传文件大小不能超过" + limitSize / (1024 * 1024) + "M！");
                return false;
            }
            if ($.inArray(ext, allowType) == -1) {
                alert("文件格式限：" + allowType.join(","));
                return false;
            }
        });
        // 当有文件被添加进队列的时候
        uploader.on('fileQueued', function(file) {
            //$pickerBtn.hide(); //隐藏上传按钮
            //$list.append('<span class="file-panel l ' + choseBtn + ' ">删除</span>');
            $list.html("上传中...");
        });
        // 文件上传失败，显示上传出错。
        uploader.on('uploadError', function(file,reason) {
            alert('上传出错:'+reason);
        });
        //当文件上传成功时触发。能接受后台返回值
        uploader.on('uploadSuccess', function(file, response) {
            uploader.removeFile(file); //删除队列中文件,解除fileNumLimit限制
            //response filter
            if (response.returnInfo && response.returnInfo.url != "") {
                var furl = Util.FileRUrl;
                $list.html("上传成功");
                //$list.parent().prev().find("a").hide();flash兼容性？
                $list.parent().prev().find("a").css({ top: "-32px" });
                setTimeout(function() {
                    var oprhtml = '<span class="fileopr filedelete" data-role="' + response.returnInfo.attachGuid + '">删除</span>|<span class="fileopr filedetail" data-url="' + furl + response.returnInfo.url + '">查看</span>';
                    $list.html(oprhtml);
                    //unbind common.js click
                    $(".filedelete").unbind('click');
                    $(".filedetail").unbind('click');
                    //delete file
                    $(".filedelete").click(function(event) {
                        var $this = $(this);
                        var fguid = $this.data("role");
                        //delete ajax
                        $.ajax({
                            url: Util.AjaxRUrl + 'deleteAttachFile',
                            type: "post",
                            dataType: "json",
                            data: {
                                param: '{attachGuid:"' + fguid + '"}'
                            },
                            success: function(data) {
                                if (data.returnInfo) {
                                    if (data.returnInfo.isok == 1) {
                                        //success:remove
                                        alert("已删除");
                                        $this.parents(".ewb-tr").find("a.webuploader-container").css({ top: "0px" });
                                        $this.parent().html("");
                                    } else {
                                        alert("删除失败");
                                    }
                                }
                            },
                            error: function(XMLHttpRequest, txtStatus, errorThrown) {
                                //console.log(XMLHttpRequest);
                            }
                        });

                    });
                    //look file
                    $(".filedetail").on('click', function() {
                        var $this = $(this);
                        var furl = $this.data("url");
                        window.open(furl, "_blank");
                    });
                }, 1000);
            }

        });
        // 当所有文件上传结束时触发。无法接受后台返回值
        uploader.on('uploadFinished', function(file, response) {
            // alert('上传完成！');
        });
        // uploader.on('uploadProgress', function(file, percentage) {
        //     var $li = $('#' + file.id),
        //         $percent = $li.find('.progress .progress-bar');

        //     // 避免重复创建
        //     if (!$percent.length) {
        //         $percent = $('<div class="progress progress-striped active">' +
        //             '<div class="progress-bar" role="progressbar" style="width: 0%">' +
        //             '</div>' +
        //             '</div>').appendTo($li).find('.progress-bar');
        //     }

        //     $li.find('p.state').text('上传中');

        //     $percent.css('width', percentage * 100 + '%');
        // });
        return uploader;
    }
})(jQuery);
